package com.fowo.api.walmart.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.*;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformItemVo;
import com.fowo.api.service.impl.NavSellOrderPlatformServiceImpl;
import com.fowo.api.service.impl.NavSellOrderServiceImpl;
import com.fowo.api.service.impl.TmpWalmartOrderGoodsServiceImpl;
import com.fowo.api.service.impl.TmpWalmartOrderServiceImpl;
import com.fowo.api.walmart.api.WalmartApi;
import com.fowo.api.walmart.api.WalmartInventoryApi;
import com.fowo.api.walmart.api.WalmartItemApi;
import com.fowo.api.walmart.entity.GetOrderDto;
import com.fowo.api.walmart.mapper.SyncWalmartMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncWalmartOrderServiceImpl extends ServiceImpl<NavSellOrderMapper, NavSellOrder> {

    @Resource
    private SysCountryMapper sysCountryMapper;
    @Resource
    private NavSellOrderServiceImpl navSellOrderService;
    @Resource
    private NavSellOrderMapper navSellOrderMapper;
    @Resource
    private ParilistMapper parilistMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private WalmartApi walmartApi;
    @Resource
    private TmpWalmartOrderServiceImpl tmpWalmartOrderService;
    @Resource
    private TmpWalmartOrderGoodsServiceImpl tmpWalmartOrderGoodsService;
    @Resource
    private SyncWalmartMapper syncWalmartMapper;
    @Resource
    private WalmartItemApi walmartItemApi;
    @Resource
    private WalmartInventoryApi walmartInventoryApi;
    @Resource
    private NavSellOrderPlatformServiceImpl navSellOrderPlatformService;

    private final IdentifierGenerator identifierGenerator = new DefaultIdentifierGenerator();

    @Transactional(rollbackFor = Exception.class)
    public void syncOrder() throws Exception {
        //删除临时表数据
        tmpWalmartOrderService.remove(null);
        tmpWalmartOrderGoodsService.remove(null);
        //拉取数据到临时表
        GetOrderDto getOrderDto = new GetOrderDto();
//        getOrderDto.setCreatedStartDate(DateUtil.formatDate(DateUtil.yesterday()));
//        getOrderDto.setCreatedEndDate(DateUtil.formatDate(DateUtil.yesterday()));
        getOrderDto.setLastModifiedStartDate(DateUtil.formatDate(DateUtil.yesterday()));
        getOrderDto.setLastModifiedEndDate(DateUtil.formatDate(new Date()));
        getOrderDto.setProductInfo("true");
        //平台发货订单
        getOrderDto.setShipNodeType("WFSFulfilled");
        walmartApi.getOrder(getOrderDto);
        //自发货订单
        getOrderDto.setShipNodeType("SellerFulfilled");
        walmartApi.getOrder(getOrderDto);
        log.info("拉取数据完成");

        //获取所有国家
        QueryWrapper<SysCountry> queryWrapper = new QueryWrapper();
        queryWrapper.isNotNull("code");
        List<SysCountry> sysCountries = sysCountryMapper.selectList(queryWrapper);
        Map<String, List<SysCountry>> collect = sysCountries.stream().collect(Collectors.groupingBy(SysCountry::getCode));

        final List<TmpWalmartOrder> orderList = tmpWalmartOrderService.list();
        final List<TmpWalmartOrderGoods> goodsList = tmpWalmartOrderGoodsService.list();
        dataHandle(collect, orderList,goodsList);
        log.info("订单数据处理完成");

        //数据插入完成 检测订单是否可合并
        navSellOrderService.splitTask();
        log.info("订单数据拆分检测完成");
        navSellOrderService.joinTask();
        log.info("订单数据合并检测完成");
    }

    /**
     * 处理订单数据
     * @param collect
     * @param orderList
     * @param goodsList
     */
    private void dataHandle(Map<String, List<SysCountry>> collect, List<TmpWalmartOrder> orderList,List<TmpWalmartOrderGoods> goodsList) throws Exception {
        for (TmpWalmartOrder order: orderList) {
            NavSellOrder navSellOrder = getNavSellOrderByPlatformOrderId(order.getPurchaseOrderId());
            if(null != navSellOrder){
                updateNavSellOrder(order,navSellOrder);
            }else{
                insertNavSellOrder(order,collect,goodsList);
            }
        }
    }

    /**
     * 新增订单
     * @param order
     * @param collect
     * @param goodsList
     */
    public void insertNavSellOrder(TmpWalmartOrder order,Map<String, List<SysCountry>> collect,List<TmpWalmartOrderGoods> goodsList){

        List<NavSellOrderDetail> detailList = new ArrayList<>();
        List<NavSellOrderPlatform> platFormList = new ArrayList<>();
//            List<NavSellOrderTransaction> transactionList = new ArrayList<>();
        NavSellOrderVo vo = new NavSellOrderVo();
        List<NavSellOrderDetailItemVo> productList = new ArrayList<>();
//            JSONObject jsonObject = JSONObject.parseObject(object.toString());
        NavSellOrder sellOrder = new NavSellOrder();
        sellOrder.setShopInfo(order.getSid());
        sellOrder.setBuyerEmail(order.getCustomerEmailId());
//            sellOrder.setCreateTime(new Date());
        sellOrder.setPaymentWay("1");//order.getPaymentTypes()
        //表结构改变 订单来源存储位置更换
        NavSellOrderPlatform navSellOrderPlatform = new NavSellOrderPlatform();
        navSellOrderPlatform.setCreateTime(new Date());
        navSellOrderPlatform.setPurchaseTime(order.getOrderDate());
        navSellOrderPlatform.setSource("1");
        navSellOrderPlatform.setPlatform("Walmart");
        navSellOrderPlatform.setPlatformOrderId(order.getPurchaseOrderId());
//            navSellOrderPlatform.setParentNavSellOrder(aLong);
        //获取物流信息
//            JSONObject address = JSONObject.parseObject(jsonObject.get("shippingInfo").toString());
        navSellOrderPlatform.setDeliveryTime(order.getEstimatedDeliveryDate());
        navSellOrderPlatform.setLatestShipTime(order.getEstimatedShipDate());
        //客选物流
//            order.getMethodCode();
//            sellOrder.setDeliveryLogistics();

        sellOrder.setDeliveryPhone(order.getPhone());
        sellOrder.setBuyerName(order.getName());
        sellOrder.setDeliveryReceipt(order.getName());
        sellOrder.setDeliveryCity(order.getCity());
        sellOrder.setDeliveryProvince(order.getState());
        List<SysCountry> sysCountries1 = collect.get(order.getCountry().equals("USA") ? "US" : order.getCountry());
        if(sysCountries1 != null && sysCountries1.size() > 0){
            sellOrder.setDeliveryCountry(sysCountries1.get(0).getId());
            navSellOrderPlatform.setCountry(sysCountries1.get(0).getId());
        }
        order.getAddressType();
        switch(order.getAddressType()){
            case "RESIDENTIAL":
                sellOrder.setDeliveryAddressType("1");
                break;
            default:
                break;
        }
        sellOrder.setDeliveryAddress1(order.getAddress1());
        sellOrder.setDeliveryAddress2(order.getAddress2());
        sellOrder.setDeliveryZipCode(order.getPostalCode());
        //根据商品数量判断订单类型
        final List<TmpWalmartOrderGoods> orderGoodsList = goodsList.stream().filter(g -> g.getCustomerOrderId().equals(order.getCustomerOrderId())).collect(Collectors.toList());
//            JSONObject orderLines = JSONObject.parseObject(jsonObject.get("orderLines").toString());
//            JSONArray objects = JSONObject.parseArray(orderLines.get("orderLine").toString());
        sellOrder.setDeliveryRealQuantity(orderGoodsList.size());
        if(orderGoodsList.size() == 1){
            sellOrder.setType("1");
        }
        if(orderGoodsList.size() > 1){
            sellOrder.setType("2");
        }

        //商品信息
        //总价
        BigDecimal decimal = BigDecimal.ZERO;
        BigDecimal taxTotal = BigDecimal.ZERO;
        String currenty = "";
        double weight = 0.00;
//            boolean isPari = true; //是否配对商品
        for (TmpWalmartOrderGoods orderGoods : orderGoodsList) {
//                JSONObject line = JSONObject.parseObject(o.toString());
            NavSellOrderDetail detail = new NavSellOrderDetail();
            detail.setPlatformOrderId(order.getPurchaseOrderId());
            detail.setReferenceId(order.getCustomerOrderId());
            detail.setCreateTime(new Date());
//                detail.setId((Long) identifierGenerator.nextId(null));
//                detail.setParentNavSellOrder(aLong);
//                JSONObject item = line.getObject("item", JSONObject.class);
            detail.setMsku(orderGoods.getSku());
            detail.setShopInfo(order.getSid());
            //根据sku匹配本地商品
//                Parilist parilist = parilistMapper.selectOne(Wrappers.lambdaQuery(Parilist.class)
//                        .eq(Parilist::getMsku,orderGoods.getSku())
//                        .eq(Parilist::getShopId,order.getSid())
//                        .eq(Parilist::getPlatforms,"Walmart")
//                        .eq(Parilist::getType,"1"));
//                if(null != parilist){
//                    detail.setSku(parilist.getSku());
//                    detail.setProductId(parilist.getProductId());
//                    detail.setImg(parilist.getImg());
//                    detail.setProductName(parilist.getProductName());
//                }else{ //本地没有匹配产品，加 商品为配对 标签
//                    isPari = false;
//                }
            //判断重量是否为空 转换为克存储
            if(orderGoods.getWeight() != null){
                if(StrUtil.equals(orderGoods.getWeightUnit(),"Pounds")){
                    weight = weight + Double.valueOf(orderGoods.getWeight()) * 453.59237;
                }
            }
            JSONObject charges = JSONObject.parseObject(orderGoods.getCharges());
            //价格
            JSONArray charge = charges.getJSONArray("charge");
            for(int i = 0 ; i < charge.size() ; i++){
                final JSONObject chargeObject = charge.getJSONObject(i);
                final String chargeType = chargeObject.getString("chargeType");
                final String chargeName = chargeObject.getString("chargeName");
                final JSONObject chargeAmount = chargeObject.getJSONObject("chargeAmount");
                final JSONObject tax = chargeObject.getJSONObject("tax");
                if(chargeType.equals("PRODUCT") && chargeName.equals("ItemPrice")){ //产品价格
                    detail.setPrice(chargeAmount.getBigDecimal("amount"));
//                        detail.setAmount(chargeAmount.getBigDecimal("amount"));
                    sellOrder.setCurrency(chargeAmount.getString("currency"));
                    if(null != tax){
                        detail.setSaleTax(tax.getJSONObject("taxAmount").getBigDecimal("amount"));
                        detail.setTax(tax.getJSONObject("taxAmount").getBigDecimal("amount"));
                    }
                }else  if(chargeType.equals("PRODUCT")){ //产品折扣
                    detail.setDiscount(chargeAmount.getBigDecimal("amount"));
                }else if(chargeType.equals("SHIPPING") && chargeName.equals("Shipping")){ //客付运费
                    detail.setDeliveryRealFreight(chargeAmount.getBigDecimal("amount"));
                }
            }
            detail.setQuantity(Integer.valueOf(orderGoods.getAmount()));
            detail.setAmount(detail.getPrice().multiply(new BigDecimal(orderGoods.getAmount())));
            detail.setUnitOfMeasurement(orderGoods.getUnitOfMeasurement());
            detail.setLineNumber(orderGoods.getLineNumber());
            detail.setSellerOrderId(orderGoods.getSellerOrderId());
            detail.setGoodsTitle(orderGoods.getProductName());
            detailList.add(detail);
            NavSellOrderDetailItemVo detailVo = new NavSellOrderDetailItemVo();
            BeanUtils.copyProperties(detail,detailVo);
            productList.add(detailVo);
        }
//            NavSellOrderTransaction transaction = new NavSellOrderTransaction();
//            transaction.setSaleTax(taxTotal);
//            transaction.setAmount(decimal);
//            transaction.setTotalAmount(decimal);
//            if(!isPari){
//                sellOrder.setTag(navSellOrderService.tagHandler(null,"4"));
//            }
//        sellOrder.setCurrency(currenty);
        sellOrder.setStatus("1");
        if(StrUtil.isNotBlank(order.getShipType()) && order.getShipType().equals("WFSFulfilled")){
            sellOrder.setStatus("5");
        }
        sellOrder.setDeliveryRealWeight(BigDecimal.valueOf(weight));
        sellOrder.setDeliveryType("2");
        sellOrder.setDeliveryCodeOrder("0");
//            transactionList.add(transaction);
        platFormList.add(navSellOrderPlatform);

        //当前数据转换为规则需要的数据格式
        BeanUtils.copyProperties(sellOrder,vo);
        List<NavSellOrderDetailItemVo> navSellOrderDetailItemVos = JSONObject.parseArray(JSON.toJSONString(detailList), NavSellOrderDetailItemVo.class);
//            List<NavSellOrderTransactionItemVo> navSellOrderTransactionItemVos = JSONObject.parseArray(JSON.toJSONString(transactionList), NavSellOrderTransactionItemVo.class);
        List<NavSellOrderPlatformItemVo> navSellOrderPlatformItemVos = JSONObject.parseArray(JSON.toJSONString(platFormList), NavSellOrderPlatformItemVo.class);
        vo.setPlatform(navSellOrderPlatformItemVos);
//            vo.setTransaction(navSellOrderTransactionItemVos);
        vo.setProduct(navSellOrderDetailItemVos);
        try {
            navSellOrderService.create(vo);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 更新订单
     * @param order
     * @param navSellOrder
     */
    public void updateNavSellOrder(TmpWalmartOrder order,NavSellOrder navSellOrder) throws Exception {
        if(order.getOrderStatus().equals("Cancelled")){
            if(navSellOrder.getStatus().equals("2") || navSellOrder.getStatus().equals("3")){
                List<Long> ids = new ArrayList<>();
                ids.add(navSellOrder.getId());
                navSellOrderService.cut(ids);
            }
            navSellOrder.setStatus("-1");
            navSellOrder.setTag(navSellOrderService.tagHandler(navSellOrder.getTag(),"12,26"));
            navSellOrderService.updateById(navSellOrder);
        }
    }

    /**
     * 根据平台单号获取订单
     * @param platformOrderId
     * @return
     */
    public NavSellOrder getNavSellOrderByPlatformOrderId(String platformOrderId) {
        NavSellOrderPlatform navSellOrderPlatform = navSellOrderPlatformService.getOne(Wrappers.lambdaQuery(NavSellOrderPlatform.class)
                .eq(NavSellOrderPlatform::getPlatformOrderId,platformOrderId)
                .eq(NavSellOrderPlatform::getPlatform,"Walmart"),false);
        if(null == navSellOrderPlatform){
            return null;
        }
        NavSellOrder navSellOrder = navSellOrderService.getById(navSellOrderPlatform.getParentNavSellOrder());
        return navSellOrder;
    }

    /**
     * 同步产品数据
     * @throws Exception
     */
    public void syncItem() throws Exception {
        syncWalmartMapper.deleteAllTemItem();
        //拉取现在商品并保存临时表
        walmartItemApi.itemReport();
        log.info("沃尔玛商品拉取完成");
        syncWalmartMapper.updateWalmartListing();
        syncWalmartMapper.insertWalmartListing();
        syncWalmartMapper.insertPariList();
        log.info("沃尔玛商品同步完成");
    }

    /**
     * 同步WFS库存
     * @throws IOException
     */
    public void syncInventory() throws IOException {
        syncWalmartMapper.deleteAllInventory();
        walmartInventoryApi.getInventoryReport();
        log.info("WFS库存数据拉取完成");

        syncWalmartMapper.updateWalmartInventory();
        syncWalmartMapper.insertWalmartInventory();
        log.info("WFS库存同步完成");
    }



}
